﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Ccr.Core;
using XcoAppSpaces.Contracts.Messaging;

namespace XcoAppSpaces.Core.Communication
{
	static class CausalityContextExtensions
	{
		private const string MessageContextCausalityName = "cMsgContext";

		public static void InstallCausalities(this CausalityContext context, MessageContext msgContext)
		{
			try
			{
				AddCausalities(context, msgContext);
			}
			catch (ArgumentException) //this is to prevent ccr causality bug
			{
				Dispatcher.ClearCausalities(); //there shouldn't be any causalities installed at this point, so clearing the causalities to prevent the bug is no problem
				AddCausalities(context, msgContext);
			}
		}

		public static void AddCausalities(this CausalityContext context, MessageContext msgContext)
		{
			if (context != null && context.Causalities != null && context.Causalities.Length > 0)
			{
				foreach (CausalityInfo cInfo in context.Causalities)
				{
					Dispatcher.AddCausality(new ExtendedCausality(cInfo.Name, cInfo.ExceptionPort, cInfo.CoordinationPort, msgContext));
				}
			}
			else
			{
				//if no causalities present, then add a replacement causality for the message context
				Dispatcher.AddCausality(new ExtendedCausality(MessageContextCausalityName, null, null, msgContext));
			}
		}



		public static void UninstallCausalities(this CausalityContext context)
		{
            if (context != null && context.Causalities != null && context.Causalities.Length > 0)
			{
				foreach (CausalityInfo cInfo in context.Causalities)
				{
					Dispatcher.RemoveCausality(cInfo.Name);
				}
			}
			else
			{
				Dispatcher.RemoveCausality(MessageContextCausalityName);
			}
		}
	}
}
